# -*- coding: UTF-8 -*-
#
# FileName     : response_snp copy
# Author       : EastsunW eastsunw@foxmail.com
# Create at    : 2024-01-17 10:47
# Last Modified: 2024-01-17 10:47
# Modified By  : EastsunW
# -------------
# Description  :
# -------------

# -*- coding: UTF-8 -*-

# FileName     : response
# Author       : EastsunW eastsunw@foxmail.com
# Create at    : 2022-04-22 18:19
# Last Modified: 2022-04-22 18:19
# Modified By  : EastsunW
# -------------
# Description  : 用于TF、gene、SNP的自动补全，输入部分名字，返回匹配结果
# -------------

import re
from flask_restful import Resource, fields, marshal_with, reqparse
from Server.Utils.MongoDB import mongo


class Hint_MNV_Class(Resource):
    # 返回数据的格式
    response_fields = {
        "mnvs": fields.List(fields.String)
    }

    @marshal_with(response_fields)
    def post(self):
        """返回TF可选列表
        Arguments：
            query (str) : 输入的内容
        Returns:
            {
                mnvs : String[]
            }
        """
        # 获取参数：当前页码，每页结果数，查询类型和查询名称
        parser = reqparse.RequestParser()
        parser.add_argument(
            'query', type=str,
            required=True,
            nullable=False
        )
        request_args = parser.parse_args()
        if not request_args["query"].startswith("MNV"):
            return {"mnvs": []}
        if len(request_args["query"]) < 4:
            return {"mnvs": []}
        bare_id = request_args["query"].split("MNV")[1][0:2]
        print(bare_id)
        if bare_id.startswith("X"):
            raw_result = mongo.db\
                .get_collection("fimo")\
                .distinct(
                    key="mnvid",
                    filter={
                        "$and": [
                            {
                                "mnvid": {
                                    "$regex": "^{}".format(re.escape(request_args['query']))
                                }
                            },
                            {
                                "chr": "X"
                            }
                        ]
                    }
                )
            return {"mnvs": list(raw_result)[0:30]}
        elif bare_id.isdigit():
            raw_result = mongo.db\
                .get_collection("fimo")\
                .distinct(
                    key="mnvid",
                    filter={
                        "$and": [
                            {
                                "mnvid": {
                                    "$regex": "^{}".format(re.escape(request_args['query']))
                                }
                            },
                            {
                                "chr": str(int(bare_id))
                            }
                        ]
                    }
                )
            return {"mnvs": list(raw_result)[0:30]}
        else:
            return {"mnvs": []}
